$(function () {
    //获取操作人的姓名及ID
    /*var loginData=JSON.parse(web.readCookie("loginData"));
    var service_name = loginData.user.username;
    var service_id = loginData.user.name;*/
    var  service_name='1';
    var customer_id = GetQueryString('customer_id');
    var receiver_province = GetQueryString('receiver_province');
    var platform = GetQueryString('platform');
    var param = GetQueryString('product_kind');
    function GetQueryString(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    };
    // 菜单切换功能
    $('.ul>li').click(function () {
    var id = $(this).attr('id');
    $(this).addClass('active').siblings('.active').removeClass('active');
    $('#'+id+'_content').show().siblings().hide();
    });
    //  根据商品获取sku列表详细信息
    $('#productList').on('click','tr',function (event) {
        event.stopPropagation();
        if($(this).find('ul.tableul').length>0){
            return false;
        }
        $(this).find('td').addClass('active');
        var spu_id = $(this).find("p.p").attr("spu_id");
        $('.li1').show();
        var html = '<ul class="tableul" spu_id="" >\n' +
            '                <li class="li2"></li>\n' +
            '                <li class = "li3">\n' +
            '                    <div class="bottom">\n' +
            '                        <span class="sl">数量：</span><input type="text" id="matchProForName" value="" class="num">件<span id="matchBtnForName" class="over">完成匹配</span>\n' +
            '                    </div>\n' +
            '                </li>\n' +
            '            </ul>';
        $(this).find('td').append(html);
        $(this).siblings('tr').find('td').removeClass('active');
        $(this).siblings('tr').find('td .tableul').remove();
        getSkuDetailList($('.tableul .li2'),spu_id);
    });
    $(document).click(function () {
        var td= $('#productList tr td.active');
        td.removeClass('active');
        td.find('ul.tableul').remove();
    })

    // 选择商品SKU
    $('#productList').on('click','.spec span',function (event) {
        event.stopPropagation();
        $(this).addClass('selected').siblings('.selected').removeClass('selected');
    })
    // 商品搜索匹配
    $("#proNameSearch").Validform({
        tiptype:2,
        callback:function(form){
            getListByName(1)
            return false;
        }
    });
    $("#proCodeSearch").Validform({
        tiptype:2,
        callback:function(form){
            getListByCode(1)
            return false;
        }
    });
    // 填写数量验证
    $('#matchProForCode').blur(function () {
        var value = $(this).val();
        var reg = /^\+?[1-9][0-9]*$/;
        if(!reg.test(value)){
            alert('请输入正整数！');
            $(this).val('');
        }
    });
    $('#productList').on('blur','#matchProForName',function () {
        var value = $(this).val();
        var reg = /^\+?[1-9][0-9]*$/;
        if(!reg.test(value)){
            alert('请输入正整数！');
            $(this).val('');
        }
    });
    // 完成匹配 
    $('#productList').on('click','#matchBtnForName',function (event) {
        event.stopPropagation();
        if($('.li2 .spec .selected').length==0){
            alert('请先选择商品规格!');
            return false;
        }
        var product_count = $('#matchProForName').val();
        if(product_count==''){
            alert('请输入匹配数量！');
            return false;
        }
        var reg = /^\+?[1-9][0-9]*$/;
        if(!reg.test(product_count)){
            alert('请输入正整数！');
            $(this).val('');
            return false;
        }
        var skucodes = $('.li2 .spec .selected').attr('sku_code');
        window.parent.dataListAdd(product_count,skucodes);
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });
    // 完成匹配
        $('#matchBtnForCode').click(function () {
            if($('#productByCode .td1').text()==''&&$('#productByCode .td2').text()=='') {
                alert('请先查找数据！');
                return false;
            }
            var product_count = $('#matchProForCode').val();
            if(product_count==''){
                alert('请输入添加数量！');
                return false;
            }
            var reg = /^\+?[1-9][0-9]*$/;
            if(!reg.test(product_count)){
                alert('请输入正整数！');
                $(this).val('');
                return false;
            }

            skucodes=$('#productByCode .td2>.detail').attr("skucode");
            console.log(skucodes);
            window.session_storage.setItem('skucodes',skucodes);
            window.session_storage.setItem('product_count',product_count);
            window.parent.dataListAdd(product_count,skucodes);
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        })
    //商品列表  商品名称
    function getListByName(page_num){
        $('.tableul').hide();
        var  skuName,skuCode='';
            skuName = $('#proNameVal').val();
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.xunjiadan.exportUrl,
            cache: false,  //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                "nowPage":page_num,
                "pageSize":10,
                "model":{
                    "skuCode":skuCode,
                    "skuName":skuName,
                    "helpCode":skuName,
                    "cityId":receiver_province,
                    "customerId":customer_id
                }
            }),
            success: function (result) {
                console.log(result);
                if(result.errorCode!='0'){
                    alert(result.errorMessage);
                    return false;
                }
                data = result.data;
                orderList(data);
                $('.M-box3').pagination({
                    pageCount: result.data.totalPage,
                    jump: true,
                    coping: true,
                    prevContent: '上页',
                    nextContent: '下页',
                    callback: function (api){
                        $.ajax({
                            contentType: "application/json",
                            type: "POST",
                            url:root.xunjiadan.searchProductName,
                            cache: false,  //禁用缓存
                            dataType: "json",
                            data: JSON.stringify({
                                "nowPage":api.getCurrent(),
                                "pageSize":10,
                                "model":{
                                    "skuCode":skuCode,
                                    "skuName":skuName,
                                    "helpCode":skuName,
                                    "cityId":receiver_province,
                                    "customerId":customer_id
                                }
                            }),
                            success: function (result) {
                                console.log(result)
                                data=result.data;
                                orderList(data);
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                alert(XMLHttpRequest);
                            }
                        });
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    };
    //商品列表   商品编码
    function getListByCode(page_num){
        var  skuName='',skuCode;
        skuCode = $('#skuCode').val();
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.xunjiadan.searchProductName,
            cache: false,  //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                "nowPage":page_num,
                "pageSize":10,
                "model":{
                    "skuCode":skuCode,
                    "skuName":skuName,
                    "helpCode":skuName,
                    "cityId":receiver_province,
                    "customerId":customer_id
                }
            }),
            success: function (result) {
                console.log(result)
                if(result.errorCode!='0'){
                    $('#tableByCode').hide();
                    alert(result.errorMessage);
                    return false;
                }else{
                    data = result.data;
                    if(data.list.length == 0){
                        $('#tableByCode').hide();
                        $('#matchBtnForCode,#sl').hide();
                        $('.td3>span,.td3>input').hide();
                        alert('暂无数据！');
                        $('#productByCode .td1').empty();
                        $('#productByCode .td2').empty();
                        return false;
                    }
                }
                $('#tableByCode').show();
                $('#matchBtnForCode,#sl').show();
                $('.td3>span,.td3>input').show();
                $('#productByCode .td1').empty().append('<img class="img" src="'+data.list[0].imgUrl+'"/>');
                $('#productByCode .td2').empty().append('<p class="detail p" skuCode="'+data.model.skuCode+'">'+data.list[0].sku_name+data.list[0].sale_attri_value+'</p>');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    };
    // 根据SKU获取不同规格 并添加
    function getSkuDetailList (ele,spu_id){
        if(receiver_province == '10'){
            var wareHouseId ='1';
        }else{
            var wareHouseId ='2';
        }
        $.ajax({
            contentType: "application/x-www-form-urlencoded",
            type: "POST",
            url:root.xunjiadan.getSkuDetailList,
            cache: false,  //禁用缓存
            dataType: "json",
            data:{
                "cityId":receiver_province,
                "customerId":customer_id,
                "spuId":spu_id,
                "platformType":platform,
                "wareHouseId":wareHouseId
            },
            success: function (result) {
                console.log(result);
                if(result.errorCode=='0'){
                    $('.tableul').show();
                    if(result.data){
                       // colorList = ;
                        specList =result.data ;
                        var html  = '';
                        html+="<div class='selects'>选择规格：</div>" ;
                        html+= "<div class='spec'>";
                          for(var i = 0;i<specList.length;i++){
                              html +='<span  sku_code="'+specList[i].sku_code+'">'+specList[i].specifications+'</span>';
                          }
                        html +="</div>";
                    }
                    ele.empty().append(html);
                };
            }
        })
    }

})


var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
function orderList(data) {
    dataSource.splice(0, dataSource.length);//清空数组
    if(data.list.length>0){
        $('.dataTables_wrapper').show();
        $('.dataTables_filter').show();
        $('#productList').show();
        $('.tableul').show();
    }else{
        $('.dataTables_wrapper').hide();
        $('.dataTables_filter').hide();
        $('#productList').hide();
        $('.tableul').hide();
    }
    $.each(data.list, function (i, field) {
        var rowData = new Array();
        rowData.push(field);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#productList').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#productList").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "render":function (data, type, row) {
                        var html = '';
                        if(data.imgUrl){
                            html+='<p class="p" spu_id="'+data.spu_id+'"><img class="img" src="'+data.imgUrl+'"/></p>'
                        }else{
                            html+='<p class="p" spu_id="'+data.spu_id+'"><img class="img" src=""/></p>';
                        }
                        html+='<p class="detail p" sku_code = "'+data.sku_code+'">'+data.sku_name+data.sale_attri_value+'</p>';
                        return html;
                    },
                    "targets": 0
                }
            ]
        });
    };
}